﻿using Vboot.Core.Module.Sys;

namespace Vboot.Core.Module.Bpm;

[ApiDescriptionSettings("Bpm", Tag = "流程引擎-模板")]
public class BpmProcTmplApi : IDynamicApiController
{
    private readonly BpmProcTmplService _service;

    public BpmProcTmplApi(BpmProcTmplService service)
    {
        _service = service;
    }
    
    [QueryParameters]
    public async Task<List<ZidName>> GetList(string type)
    {
        string sql = "select id,name from bpm_proc_tmpl where type=@type";
        return await _service.repo.Context.SqlQueryable<ZidName>(sql)
            .AddParameters(new [] {new SugarParameter("@type", type)})
            .ToListAsync();
    }

    [QueryParameters]
    public async Task<dynamic> Get(string type,string name)
    {
        var pp=XreqUtil.GetPp();
        var items = await _service.repo.Context.Queryable<BpmProcTmpl,SysOrg,SysOrg> 
            ((t,o,o2)=> new JoinQueryInfos(
                JoinType.Left, o.id == t.crmid,
                JoinType.Left, o2.id == t.upmid))
            .WhereIF(!string.IsNullOrWhiteSpace(type), t => t.type == type)
            .WhereIF(!string.IsNullOrWhiteSpace(name), t => t.name.Contains(name.Trim()))
            .OrderBy(t => t.crtim, OrderByType.Desc)
            .Select((t,o,o2) 
                => new {t.id, t.name, t.crtim, t.uptim,crman=o.name,upman=o2.name,t.notes})
            .ToPageListAsync(pp.page, pp.pageSize, pp.total);
        return RestPageResult.Build(pp.total.Value, items);
    }
    

    public async Task<BpmProcTmpl> GetOne(string id)
    {
        var main = await _service.SingleAsync(id);
        return main;
    }

    public async Task<string> Post(BpmProcTmpl main)
    {
        main.chxml = "<?xml version=\"1.0\" encoding=\"gb2312\"?>"
                     + "\n<process" + main.orxml.Split("bpmn2:process")[1]
                         .Replace("bpmn2:", "").Replace("activiti:", "") + "process>";
        return await _service.InsertAsync(main);
    }

    public async Task<string> Put(BpmProcTmpl main)
    {
        main.chxml = "<?xml version=\"1.0\" encoding=\"gb2312\"?>"
                     + "\n<process" + main.orxml.Split("bpmn2:process")[1]
                         .Replace("bpmn2:", "").Replace("activiti:", "") + "process>";
        return await _service.UpdateAsync(main);
    }

    public async Task Delete(string ids)
    {
        await _service.DeleteAsync(ids);
    }
}